package cn.cew.bytespyserver.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author chenenwei
 * @version 1.0.0
 * @description TODO
 * @createTime 2022-10-15 16:45:00
 */
@Slf4j
@Service
public class AgentServerSocket {

    @Resource
    private WebsocketServer websocketServer;

    public static BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10000);

    public void start(int port) throws IOException {

        //定义一个ServerSocket监听
        ServerSocket server = new ServerSocket(port);
        send();
        log.info("【目标监控服务启动】 端口：{}", port);
        while (true) {
            //server尝试接收其他Socket的连接请求，server的accept方法是阻塞式的
            Socket socket = server.accept();
            //每接收到一个Socket就建立一个新的线程来处理它
            new Thread(new AgentServerSocket.Task(socket)).start();
        }
    }

    /**
     * 处理Socket请求
     */
    public static class Task implements Runnable {

        private Socket socket;

        public Task(Socket socket) {
            this.socket = socket;

        }

        public void run() {
            try {
                handleSocket();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        /**
         * 跟客户端Socket进行通信
         * @throws Exception
         */
        private void handleSocket() throws Exception {
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String temp;
            int index;
            while ((temp=br.readLine()) != null) {
                //遇到eof时就结束接收
                if ((index = temp.indexOf("EOF")) != -1) {
                    sb.append(temp, 0, index).append(System.getProperty("line.separator"));
                    break;
                }
                sb.append(temp).append(System.getProperty("line.separator"));
            }
            log.info("【客户端消息】 {}", sb.toString());
            queue.add(sb.toString());
            br.close();
            socket.close();
        }
    }

    public void send () {

        new Thread(() -> {
            while (true) {
                try {
                    websocketServer.sendAllMessage(AgentServerSocket.queue.take());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
        }).start();
    }
}
